<?php
/**
 * @Author: anchen
 * @Date:   2016-04-05 21:01:55
 * @Last Modified by:   anchen
 * @Last Modified time: 2016-05-24 11:01:13
 */




require 'vendor/autoload.php';

use Sinergi\BrowserDetector\Browser;
use Sinergi\BrowserDetector\Os;
use Sinergi\BrowserDetector\Device;
use Sinergi\BrowserDetector\Language;



@ini_set('date.timezone','Asia/Shanghai');


define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

if(!IS_AJAX) {die('Restricted access');}

$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false) die('Restricted access');

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


$response = array(
		'flag' => true,
		'data' => '',
		'step'=>'',
		'time1'=>'',
		'time2'=>'',
		'spend'=>'',
		'sendtime'=>'',
		'receivetime'=>'',
		'spend2'=>'',
		'maxmind' =>'',
		'returnmsg'=>''
);
$t1 = time();

$response['sendtime'] = time();

try {

		$clockmsg = postdata();


		$response['receivetime'] = time();
		$response['spend2'] = time() - $t1;
		$response['returnmsg'] = $clockmsg;
		$response['ip'] = get_client_ip();

		if($clockmsg){
			$resipjson = json_decode($clockmsg,true);
			$retmsg = $resipjson['msg'];
			$response['step'] = $resipjson['step'];
			$response['time1'] = $resipjson['time1'];
			$response['time2'] = $resipjson['time2'];
			$response['spend'] = $resipjson['spend'];
			$response['maxmind'] = $resipjson['maxmind'];

			//$retmsg = "showC";

			if($retmsg == "notshow"){
				$response['data'] = "";
				$response['flag'] = false;

			}else if($retmsg == "showB"){
				$response['data'] = file_get_contents('./showB.html', FILE_USE_INCLUDE_PATH);

			}else if($retmsg == "showC"){
				$response['data'] = file_get_contents('./showC.html', FILE_USE_INCLUDE_PATH);
			}else {
				$response['data'] = "";
				$response['flag'] = false;
			}

		}else{

			$response['data'] = "";
			$response['step'] = "error";
			$response['flag'] = false;

		}
		//$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);

		echo json_encode($response);
}catch (Exception $e) {

	$response['data'] = "";
	$response['step'] = "error";
	$response['flag'] = false;


	echo json_encode($response);
	return;
}









//POST data
function postdata(){
	// set post fields

	$browser = new Browser();
	$browsername = $browser->getName();
	$browserversion = $browser->getVersion();

	$os = new Os();
	$osname = $os->getName();
	$osversion = $os->getName();

	$device = new Device();
	$devicename = $device->getName();

	$language = new Language();
	$bwlanguage = $language->getLanguage();

	//gclid参数
	$gclid = "";
	$timezone = "";
	$clockurl = "";

	if (isset($_GET['time_zone'])) {
		$timezone = $_GET['time_zone'];
	}



	if(isset($_SERVER['HTTP_REFERER'])){
		$parts = parse_url($_SERVER['HTTP_REFERER']);

		$urlstr = explode('?', $_SERVER['HTTP_REFERER']);

		$clockurl = $urlstr[0];

		$clockurl = str_replace("http://www.","http://",$clockurl);

		if(isset($parts['query'])){
			parse_str($parts['query'], $query);
			$gclid = $query['gclid'];
		}
	}
	//$clockurl = 'http://' .$_SERVER['HTTP_REFFER'] . $_SERVER['PHP_SELF'];

	$sendip = get_ip_address();

	if($sendip == '23.91.24.154' || $sendip == '103.20.194.60' || $sendip == '::1'){
		//$sendip = '166.137.139.120';
		//$sendip = '23.91.24.154';
	}

	$post = [
			'browsername' => $browsername,
			'browserversion' => $browserversion,
			'osname'   => $osname,
			'osversion' => $osversion,
			'devicename' => $devicename,
			'bwlanguage' => $bwlanguage,
			'ipaddress' => $sendip,
			'gclid' => $gclid,
			'clockurl' => $clockurl,
			'cookie' => getcookie(),
			'time_zone' => $timezone
	];


	$ch = curl_init('http://www.nbxtrack.com/clock/check.php');

	//$ch = curl_init('http://localhost:8080/app/clock/check.php');

	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10); //timeout in seconds
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

	// execute!
	//echo "send:";
	//$t1 = time();
	//echo  $t1;
	$response = curl_exec($ch);

	//$t2 = time();
	//echo "<br>";
	//echo "finish:";
	//echo $t2;
	//echo "<br>";
	//echo $t2 - $t1;

	$errno = curl_errno($ch);
    $err  = curl_error($ch);
	// close the connection, release resources used
	curl_close($ch);


	if($errno)
	{
		return "";
	}else{


		return  $response;
	}
	// do anything you want with your response
	//var_dump($response);
	//return $response;
}


function get_ip_address() {
    $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
    foreach ($ip_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                // trim for safety measures
                $ip = trim($ip);
                // attempt to validate IP
                if (validate_ip($ip)) {
                    return $ip;
                }
            }
        }
    }
    return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
}
/**
 * Ensures an ip address is both a valid IP and does not fall within
 * a private network range.
 */
function validate_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
        return false;
    }
    return true;
}




//获取IP
function get_client_ip() {

	$ipaddress = '';
	if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'])
		$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
		else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'])
			$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
			else if(isset($_SERVER['HTTP_X_FORWARDED']) && $_SERVER['HTTP_X_FORWARDED'])
				$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
				else if(isset($_SERVER['HTTP_FORWARDED_FOR']) && $_SERVER['HTTP_FORWARDED_FOR'])
					$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
					else if(isset($_SERVER['HTTP_FORWARDED']) && $_SERVER['HTTP_FORWARDED'])
						$ipaddress = $_SERVER['HTTP_FORWARDED'];
						else if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'])
							$ipaddress = $_SERVER['REMOTE_ADDR'];
							else
								$ipaddress = 'UNKNOWN';
								return $ipaddress;
}

function getcookie(){

	$cookie = 0;

	if (!isset($_COOKIE['c']) || !isset($_COOKIE['t']))
	{
		$cookie = 1;
		setcookie("c",$cookie,  time()+86400);
	    setcookie("t",time(),time()+86400);

	}else if(isset($_COOKIE['c']) && isset($_COOKIE['t']))
	{
	  $cookie = $_COOKIE['c']+1;
	  //echo $_COOKIE['t'];
	  $expiretime = 86400 + $_COOKIE['t'];
	  setcookie("c", $cookie,$expiretime);
	  //setcookie("t",time(),$expiretime);

	}
	return $cookie;
}


function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
